import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import ReactQuill from 'react-quill'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import { http } from '../../utils'

// 导入封装好的 Channel 组件
import Channel from '../../components/Channel'

import 'react-quill/dist/quill.snow.css'
import './index.scss'

const ArticlePublish = () => {
  const [selectedValue, setSelectedValue] = useState(1)
  const [fileList, setFileList] = useState([])
  const [formRef] = Form.useForm()

  const params = useParams()

  // 是否为编辑
  const isEdit = typeof params.id !== 'undefined'

  useEffect(() => {
    const getArticleById = async () => {
      try {
        // 从 路由信息 中获取到 路由参数 id 的值
        const id = params.id
        const res = await http.get(`/mp/articles/${id}`)

        const { cover } = res.data.data
        const { images, type } = cover
        const fileList = images.map(url => {
          return {
            url
          }
        })

        setFileList(fileList)
        setSelectedValue(type)
        // instance 实例
        formRef.setFieldsValue({
          ...res.data.data,
          type
        })
      } catch (e) {
        message.warning('服务器出问题了，可能是因为该文章被删除了，换一个试试')
      }
    }

    if (isEdit) {
      getArticleById()
    }
  }, [isEdit, params, formRef])

  // 表单提交
  const onFinish = values => {
    save(values, false)
  }

  // 处理封面
  const changeImageType = e => {
    const selectedValue = e.target.value
    setSelectedValue(selectedValue)
  }

  // 上传图片的方法的参数，是一个对象（data）
  const uploadImages = data => {
    setFileList([...data.fileList])
  }

  // 存入草稿
  const saveDraft = async () => {
    try {
      const values = await formRef.validateFields()
      save(values, true)
    } catch (e) {}
  }

  // 封装保存数据的方法 - 用来实现文章的编辑、发布以及相应的存入草稿功能
  const save = async (values, isDraft) => {
    const id = params.id
    const { type, ...restValues } = values
    const images = fileList.map(item => {
      if (item.url) {
        return item.url
      }
      return item.response.data.url
    })
    const cover = {
      type: type,
      images
    }
    const data = {
      ...restValues,
      cover
    }

    let url = ''
    let msg = ''

    if (isEdit) {
      // 编辑时
      if (isDraft) {
        // 草稿
        url = `/mp/articles/${id}?draft=true`
        msg = '存入草稿成功'
      } else {
        // 非草稿
        url = `/mp/articles/${id}`
        msg = '修改成功'
      }
      const res = await http.put(url, data)

      if (res.data.message.toLowerCase() === 'ok') {
        message.success(msg, 1)
      }
    } else {
      // 发布时
      if (isDraft) {
        // 草稿
        url = '/mp/articles?draft=true'
        msg = '存入草稿成功'
      } else {
        url = '/mp/articles'
        msg = '发布成功'
      }

      const res = await http.post(url, data)
      if (res.data.message.toLowerCase() === 'ok') {
        message.success(msg, 1)
      }
    }
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* span 表示占用了 4 格，一共 24 格 */}
        <Form
          form={formRef}
          labelCol={{ span: 4 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
        >
          {/* <Form.Item hidden name="id">
              <Input type="hidden" />
            </Form.Item> */}
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400} />
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeImageType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>

            {/* 上传图片组件 */}
            {selectedValue !== 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                maxCount={selectedValue}
                action="http://geek.itheima.net/v1_0/upload"
                onChange={uploadImages}
                fileList={fileList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '修改文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default ArticlePublish
